package net.xxcl.exam.controller;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.xxcl.exam.pojo.Criteria;
import net.xxcl.exam.pojo.Question;
import net.xxcl.exam.service.QuestionService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.*;

/**
 * User: 夏汛
 * Date: 11-12-24
 * Time: 下午12:06
 */
@Controller
@RequestMapping("/tiku")
public class TikuController {
    @Autowired
    private QuestionService questionService;

    @RequestMapping(value="/importTikuFromExcel",method= RequestMethod.POST)
    public void importTikuFromExcel(MultipartHttpServletRequest request,HttpServletResponse response){
        MultipartFile file = request.getFile("file");
        int kemuid = Integer.parseInt(request.getParameter("kemuid"));
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if(!file.isEmpty()){
                String fileHz = "";
                //如果文件类型是excel 2003，后缀名设置为.xls
                if(file.getContentType().equals("application/vnd.ms-excel")){
                    fileHz = ".xls";
                }
                else {
                    out.print("{'info':'暂时只能支持excel 2003的格式'}");
                    return;
                }
                String filePath = request.getSession().getServletContext().getRealPath("userUpload");
                String fileName = UUID.randomUUID() + fileHz;

                File dirPath = new File(filePath);
                if (!dirPath.exists()) {
                    dirPath.mkdirs();
                }
                String realPath = filePath+"\\"+fileName;
                File saveFile = new File(realPath);
                FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
                out.print("{'info':'"+importToDB(realPath,kemuid)+"'}");
            } else {
                out.print("{'info':'你上传的是一个空文件'}");
            }
        } catch(Exception e) {
            e.printStackTrace();
            out.print("{'info':'服务器太忙了，导入失败！'");
        } finally {
            if(out!=null){
                out.flush();
                out.close();
            }
        }
        return;
    }

    @RequestMapping(value = "/tikus",method= RequestMethod.POST)
    public @ResponseBody
    Map<String,Object> getKemus(@RequestParam("start") Integer start,
                                @RequestParam("limit") Integer limit,
                                @RequestParam(value = "title",required = false) String title,
                                @RequestParam(value = "kemuid",required = false) Integer kemuid,
                                @RequestParam(value = "type",required = false) Integer type,
                                @RequestParam(value = "zhang",required = false) Integer zhang){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        //加上查询条件
        if(!(title==null || title.equals(""))) criteria.put("blurredTitle","%"+title+"%");
        if(kemuid!=null) criteria.put("kemuid",kemuid);
        if(type!=null) criteria.put("type",type);
        if(zhang!=null) criteria.put("zhang",zhang);
        int total = questionService.countByExample(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        List<Question> list = questionService.selectByExample(criteria);
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    private String importToDB(String fileToBeRead,int kemuId){
        String message = "";    //返回的信息
        int totalSuccess = 0;   //导入成功条数
        int total = 0;          //总条数
        String errorLine = "";  //错误的行号
        try{
            //创建对工作薄的引用
            Workbook book = Workbook.getWorkbook(new File(fileToBeRead));
            //创建对第一张工作表的引用
            Sheet sheet = book.getSheet(0);
            //获取有效行数（可能中间有空行，因此不等于总条数）
            int rowNumber = sheet.getRows();
            //i=1开始循环，默认第一行为标题行，不读取
            for(int i=1;i<rowNumber;i++){
                //获取行数据
                Cell[] cells = sheet.getRow(i);
                //第一列为设置的必选，如果该列没有内容，那么认为该行是空行
                if(cells[0].getContents()==null || cells[0].getContents().equals("")){
                    continue;
                }
                total += 1;
                try{
                    questionService.saveExcelRow(cells,kemuId);
                    totalSuccess += 1;
                } catch (RuntimeException e){
                    errorLine += ","+(total+1);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        message += "导入成功"+totalSuccess+"条记录！<br />";
        if(!errorLine.equals("")){
            //用substring(1)是为了去掉最前边的逗号
            message += "导入失败"+(total-totalSuccess)+"条记录!<br />失败的行："+errorLine.substring(1);
        }
        return message;
    }
}
